package com.raise.drive.commons.captcha.springmvc;

import com.octo.captcha.service.image.ImageCaptchaService;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.raise.drive.commons.web.springmvc.view.JpegView;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

public class CaptchaController implements Controller {

  private ImageCaptchaService imageCaptchaService;

  public void setImageCaptchaService(ImageCaptchaService imageCaptchaService) {
    this.imageCaptchaService = imageCaptchaService;
  }

  public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {

    // captcha
    ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
    byte[] captchaChallengeAsJpeg = null;
    try {

      // get the session id that will identify the generated captcha.
      String captchaId = request.getSession().getId();

      // call the ImageCaptchaService getChallenge method
      BufferedImage challenge = imageCaptchaService.getImageChallengeForID(captchaId);

      // a jpeg encoder
      JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream);
      jpegEncoder.encode(challenge);
      captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
    } catch (Exception e) {
      e.printStackTrace();
    }

    return new ModelAndView(new JpegView(),
        JpegView.BYTES_KEY, captchaChallengeAsJpeg);
  }
}
